<?php
/**
 * 首屏广告
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/6/3
 * @copyright PanxSoft Inc.
 */
namespace App\Http\Controllers\Admin\V1;


use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\V1\DevicePreset\DevicePresetDataRequest;
use App\Models\Device;
use App\Models\DevicePreset;
use App\Models\DevicePresetDescription;
use App\Services\Utils\Transaction;
use Illuminate\Http\Request;

class DevicePresetController extends ApiController
{
    const ROUTES = [
        'index'   => 'admin.v1.DevicePreset.index',
        'create'  => 'admin.v1.DevicePreset.create',
        'store'   => 'admin.v1.DevicePreset.store',
        'update'  => 'admin.v1.DevicePreset.update',
        'destroy' => 'admin.v1.DevicePreset.destroy',
    ];

    public function index()
    {
        $device_presets = (new DevicePreset)
            ->oldest('sort_order')
            ->latest('created_at')
            ->latest('is_show')
            ->with('devicePresetDescriptions')
            ->paginate(\request()->get('per_page') ?: 15);

        return $this->response(compact('device_presets'));
    }

    public function create()
    {
        $devices = (new Device)
            ->latest('sort_order')
            ->oldest('created_at')
            ->get();

        return $this->response(compact('devices'));
    }

    /**
     * @param DevicePresetDataRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(DevicePresetDataRequest $request)
    {
        $device_preset = Transaction::handle(function () use ($request) {
            $device_preset = (new DevicePreset)
                ->create($this->assembleDevicePresetStoreData($request));

            (new DevicePresetDescription)
                ->insert($this->assembleDevicePresetDescriptionStoreData($device_preset, $request));

            return $device_preset;
        });

        return $this->response(compact('device_preset'));
    }

    /**
     * @param DevicePresetDataRequest $request
     * @param $key
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function update(DevicePresetDataRequest $request, $key)
    {
        $device_preset = (new DevicePreset)->find($key);
            $this->checkItemExist($device_preset, trans('checker.admin.device_preset'));

        $updated = Transaction::handle(function () use ($device_preset, $request) {
            $device_preset->devicePresetDescriptions()->delete();

            (new DevicePresetDescription)
                ->insert($this->assembleDevicePresetDescriptionStoreData($device_preset, $request));

            return $device_preset->update($this->assembleDevicePresetStoreData($request));
        });

        return $this->response(compact('device_preset', 'updated'));
    }

    /**
     * @param $key
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy($key)
    {
        $device_preset = (new DevicePreset)->find($key);
            $this->checkItemExist($device_preset, trans('checker.admin.device_preset'));

        $deleted = Transaction::handle(function () use ($device_preset) {
            $device_preset->devicePresetDescriptions()->delete();

            return $device_preset->delete();
        });

        return $this->response(compact('deleted'));
    }

    /**
     * @param Request $request
     *
     * @return array
     */
    private function assembleDevicePresetStoreData(Request $request): array
    {
        $data = $request->only([
            'device_id', 'preset', 'sort_order', 'is_show', 'name', 'logo',
            'color_temperature', 'luminance'
        ]);

        if (is_string($data['preset'])) {
            $data['preset'] = json_decode($data['preset']);
        }

        return $data;
    }

    private function assembleDevicePresetDescriptionStoreData(DevicePreset $device_preset,
                                                              DevicePresetDataRequest $request): array
    {
        $descriptions = $request->descriptions;

        return array_map(function (array $description, int $language_id) use ($device_preset) {
            return [
                'device_preset_id' => $device_preset->getKey(),
                'language_id'      => $language_id,
                'name'             => $description['name'],
            ];
        }, $descriptions, array_keys($descriptions));
    }
}